package com.bdq.basic.infrastructure.config;

import cn.hutool.core.util.StrUtil;
import com.bdq.common.constants.Constant;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author malei
 * @date 2024-05-04 13:53
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<String> tokenHolder = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(Constant.HeaderField.token);
        if (StrUtil.isNotBlank(token)) {
            tokenHolder.set(token);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // Nothing needed here
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        tokenHolder.remove();
    }

    public static String getToken() {
        return tokenHolder.get();
    }
}

